package cn.pzhuWEB.llk.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;

@Component
@WebFilter("/*")
public class SensitiveWordsFilter implements Filter {
    ArrayList<String> sensitiveWords = new ArrayList<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
        String sensitiveWordsPath = servletContext.getRealPath("/WEB-INF/classes/words.txt");
        try {
            BufferedReader io = new BufferedReader(new FileReader(sensitiveWordsPath));
            String line = null;
            while ((line = io.readLine()) != null && !line.equals("")) {
                sensitiveWords.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        ServletRequest proxy_req = (ServletRequest) Proxy.newProxyInstance(servletRequest.getClass().getClassLoader(), servletRequest.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (method.getName().equals("getParameter")) {
                    String value = (String) method.invoke(servletRequest, args);
                    if (value != null) {
                        for (String str : sensitiveWords) {
                            if (value.contains(str)) {
                                value = value.replaceAll(str, "***");
                            }
                        }
                    }
                    return value;
                }
                return method.invoke(servletRequest, args);
            }
        });
        filterChain.doFilter(proxy_req,servletResponse);
    }

    @Override
    public void destroy() {
    }
}
